import 'package:amap_map_fluttify/amap_map_fluttify.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:C20Driver/event/event_bus.dart';
import 'package:C20Driver/routers/navigator_util.dart';
import 'package:C20Driver/service/request.dart';
import 'package:C20Driver/utils/locate_info.dart';
import 'package:C20Driver/utils/permission_handler.dart';
import 'package:C20Driver/utils/utils.dart';
import 'package:C20Driver/widget/spinkit.dart';
import 'package:url_launcher/url_launcher.dart';
import 'package:qrscan/qrscan.dart' as scanner;

/// 确定已经接到乘客
class CarpoolPickupPassengers extends StatefulWidget {
  final String id;
  final String type;
  CarpoolPickupPassengers({this.id, this.type});
  @override
  _CarpoolPickupPassengersState createState() =>
      _CarpoolPickupPassengersState();
}

class _CarpoolPickupPassengersState extends State<CarpoolPickupPassengers>
    with TickerProviderStateMixin {
  AmapController _amapController;
  List<Marker> _markers = [];

  AnimationController pickUpPassengersController; //  去接乘客控制器
  Animation<double> pickUpPassengersAnimation; // 去接乘客动画

  AnimationController carpoolJourneyController; //  行程中控制器
  Animation<double> carpoolJourneyAnimation; // 行程中动画

  var _getData;

  /// 监听Bus触发事件
  var _themeModelscription;
  String _appbarTitle = '';

  @override
  void initState() {
    super.initState();
    _getData = getUserRideOrderInfo();

    /// 去接乘客页面
    pickUpPassengersController =
        AnimationController(vsync: this, duration: Duration(seconds: 1))
          ..addListener(() {
            setState(() {});
          })
          ..addStatusListener((status) {
            carpoolJourneyController.forward();
          });

    /// 去接乘客页面
    carpoolJourneyController =
        AnimationController(vsync: this, duration: Duration(seconds: 1))
          ..addListener(() {
            setState(() {});
          });

    if (widget.type == '0010') {
      pickUpPassengersAnimation = Tween<double>(begin: 0.0, end: -350.0)
          .animate(CurvedAnimation(
              parent: pickUpPassengersController,
              curve: Curves.linearToEaseOut));
      carpoolJourneyAnimation = Tween<double>(begin: -350.0, end: 0.0).animate(
          CurvedAnimation(
              parent: carpoolJourneyController, curve: Curves.linearToEaseOut));
      _appbarTitle = "去接乘客";
    }

    if (widget.type == '0020') {
      carpoolJourneyAnimation = Tween<double>(begin: 0.0, end: -350.0).animate(
          CurvedAnimation(
              parent: carpoolJourneyController, curve: Curves.linearToEaseOut));
      pickUpPassengersAnimation = Tween<double>(begin: -350.0, end: 0.0)
          .animate(CurvedAnimation(
              parent: pickUpPassengersController,
              curve: Curves.linearToEaseOut));
      _appbarTitle = "订单进行中";
    }

    _themeModelscription = eventBus.on<SetHitchRichProgress>().listen((event) {
      if (event.state == 1) {
        // 接到乘客出发
        pickUpPassengersController.forward();
        _appbarTitle = "订单进行中";
      }
    });
  }

  Future getUserRideOrderInfo() async {
    return await Request.getUserRideOrderInfo(widget.id);
  }

  /// 接到乘客
  void _receivePassenger(String id) {
    showDialog(
        context: context,
        builder: (context) => AlertDialog(
              title: Text('确定已经接到乘客'),
              actions: <Widget>[
                FlatButton(
                  child: Text('还未接到'),
                  onPressed: () => Navigator.pop(context, false),
                ),
                FlatButton(
                  child: Text('确定'),
                  onPressed: () {
                    Request.receivePassenger(context, id);
                  },
                ),
              ],
            ));
  }

  @override
  Widget build(BuildContext context) {
    return WillPopScope(
        child: Scaffold(
          appBar: PreferredSize(
            child: AppBar(
              title: Text('$_appbarTitle'),
              elevation: 0.0,
            ),
            preferredSize: Size.fromHeight(ScreenUtil().setWidth(100.0)),
          ),
          body: Container(
            child: FutureBuilder(
                future: _getData,
                builder: (BuildContext context, AsyncSnapshot snapshot) {
                  if (snapshot.hasData) {
                    var dataInfo = snapshot.data;
                    return Stack(
                      children: <Widget>[
                        Container(
                          width: double.infinity,
                          height: double.infinity,
                          padding: EdgeInsets.only(
                              bottom: ScreenUtil().setWidth(500.0)),
                          child: _waitingForRideAmap(dataInfo),
                        ),

                        /// 去接乘客
                        Positioned(
                          bottom: pickUpPassengersAnimation.value,
                          left: ScreenUtil().setWidth(20.0),
                          child: _pickUpPassengers(dataInfo),
                        ),

                        /// 行程中
                        Positioned(
                          bottom: carpoolJourneyAnimation.value,
                          left: ScreenUtil().setWidth(20.0),
                          child: _carpoolJourneyProgress(dataInfo),
                        ),
                      ],
                    );
                  } else {
                    return Spinkit();
                  }
                }),
          ),
        ),
        onWillPop: () async {
          Navigator.of(context).popUntil(ModalRoute.withName("/indexPage"));
          return null;
        });
  }

  /// 去接乘客
  Widget _pickUpPassengers(dataInfo) {
    return Container(
      alignment: Alignment.center,
      child: Column(
        children: <Widget>[
          Container(
            width: ScreenUtil().setWidth(710.0),
            height: ScreenUtil().setWidth(100.0),
            decoration: BoxDecoration(
              color: Colors.white,
              borderRadius: BorderRadius.circular(6.0),
              boxShadow: <BoxShadow>[
                //设置阴影
                BoxShadow(
                  color: Colors.black26, //阴影颜色
                  blurRadius: 10.0, //阴影大小
                ),
              ],
            ),
            child: Row(
              children: <Widget>[
                SizedBox(width: ScreenUtil().setWidth(30.0)),
                Icon(
                  Icons.volume_up,
                  color: Colors.black26,
                  size: ScreenUtil().setSp(44.0),
                ),
                SizedBox(
                  width: ScreenUtil().setWidth(10.0),
                ),
                Text(
                  '请在时间内去接乘客',
                  style: TextStyle(
                    fontSize: ScreenUtil().setSp(30.0),
                    color: Colors.black45,
                  ),
                ),
              ],
            ),
          ),
          SizedBox(height: ScreenUtil().setWidth(20.0)),
          Container(
            width: ScreenUtil().setWidth(710.0),
            decoration: BoxDecoration(
              color: Colors.white,
              borderRadius: BorderRadius.circular(6.0),
              boxShadow: <BoxShadow>[
                //设置阴影
                BoxShadow(
                  color: Colors.black26, //阴影颜色
                  blurRadius: 10.0, //阴影大小
                ),
              ],
            ),
            child: Column(
              children: <Widget>[
                SizedBox(height: ScreenUtil().setWidth(30.0)),
                _orderInfo(dataInfo),
                SizedBox(height: ScreenUtil().setWidth(30.0)),
                Divider(height: ScreenUtil().setWidth(1.0)),
                SizedBox(height: ScreenUtil().setWidth(30.0)),
                _orderProcessing(dataInfo),
                SizedBox(height: ScreenUtil().setWidth(30.0)),
                MaterialButton(
                  minWidth: ScreenUtil().setHeight(500.0),
                  height: ScreenUtil().setHeight(80.0),
                  color: Color.fromARGB(255, 255, 153, 0),
                  child: Text(
                    '接到乘客',
                    style: TextStyle(
                      color: Colors.white,
                      fontSize: ScreenUtil().setSp(35.0),
                    ),
                  ),
                  // onPressed: () {
                  //   // pickUpPassengersController.forward();
                  //
                  // },
                  onPressed: () => _receivePassenger(dataInfo['order_id']),
                ),
                SizedBox(height: ScreenUtil().setWidth(30.0)),
              ],
            ),
          ),
        ],
      ),
    );
  }

  /// 行程中
  Widget _carpoolJourneyProgress(dataInfo) {
    return Container(
      alignment: Alignment.center,
      child: Column(
        children: <Widget>[
          Container(
            width: ScreenUtil().setWidth(710.0),
            height: ScreenUtil().setWidth(100.0),
            decoration: BoxDecoration(
              color: Colors.white,
              borderRadius: BorderRadius.circular(6.0),
              boxShadow: <BoxShadow>[
                //设置阴影
                BoxShadow(
                  color: Colors.black26, //阴影颜色
                  blurRadius: 10.0, //阴影大小
                ),
              ],
            ),
            child: Row(
              children: <Widget>[
                SizedBox(
                  width: ScreenUtil().setWidth(30.0),
                ),
                Icon(
                  Icons.volume_up,
                  color: Colors.black26,
                  size: ScreenUtil().setSp(44.0),
                ),
                SizedBox(
                  width: ScreenUtil().setWidth(10.0),
                ),
                Text(
                  '行程中，请注意安全',
                  style: TextStyle(
                    fontSize: ScreenUtil().setSp(30.0),
                    color: Colors.black45,
                  ),
                ),
              ],
            ),
          ),
          SizedBox(
            height: ScreenUtil().setWidth(20.0),
          ),
          Container(
            width: ScreenUtil().setWidth(710.0),
            decoration: BoxDecoration(
              color: Colors.white,
              borderRadius: BorderRadius.circular(6.0),
              boxShadow: <BoxShadow>[
                //设置阴影
                BoxShadow(
                  color: Colors.black26, //阴影颜色
                  blurRadius: 10.0, //阴影大小
                ),
              ],
            ),
            child: Column(
              children: <Widget>[
                SizedBox(
                  height: ScreenUtil().setWidth(30.0),
                ),
                _orderInfo(dataInfo),
                SizedBox(
                  height: ScreenUtil().setWidth(30.0),
                ),
                Divider(
                  height: ScreenUtil().setWidth(1.0),
                ),
                SizedBox(
                  height: ScreenUtil().setWidth(30.0),
                ),
                _orderProcessing(dataInfo),
                SizedBox(
                  height: ScreenUtil().setWidth(30.0),
                ),
              ],
            ),
          ),
        ],
      ),
    );
  }

  /// 订单信息
  Widget _orderInfo(dataInfo) {
    return Container(
      padding: EdgeInsets.only(
        left: ScreenUtil().setWidth(30.0),
        right: ScreenUtil().setWidth(30.0),
      ),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: <Widget>[
          Container(
            width: ScreenUtil().setWidth(430.0),
            child: Column(
              children: <Widget>[
                Container(
                  width: ScreenUtil().setWidth(400.0),
                  child: Text(
                    '${dataInfo["departure_date"]}出发(${dataInfo["people_number"]}人)',
                    style: TextStyle(
                        fontSize: ScreenUtil().setSp(24.0),
                        color: Colors.black,
                        fontWeight: FontWeight.w700),
                  ),
                ),
                SizedBox(height: ScreenUtil().setHeight(10.0)),
                Row(
                  children: <Widget>[
                    Container(
                      width: ScreenUtil().setWidth(13.0),
                      height: ScreenUtil().setHeight(13.0),
                      decoration: BoxDecoration(
                          color: Color.fromARGB(255, 36, 142, 247),
                          shape: BoxShape.circle),
                    ),
                    SizedBox(width: ScreenUtil().setWidth(15.0)),
                    Container(
                      width: ScreenUtil().setWidth(400.0),
                      child: Text(
                        '${dataInfo["dep_are"]}',
                        maxLines: 1,
                        overflow: TextOverflow.ellipsis,
                        style: TextStyle(
                            fontSize: ScreenUtil().setSp(28.0),
                            color: Colors.black),
                      ),
                    ),
                  ],
                ),
                SizedBox(height: ScreenUtil().setHeight(10.0)),
                Row(
                  children: <Widget>[
                    Container(
                      width: ScreenUtil().setWidth(13.0),
                      height: ScreenUtil().setHeight(13.0),
                      decoration: BoxDecoration(
                          color: Color.fromARGB(255, 36, 142, 247),
                          shape: BoxShape.circle),
                    ),
                    SizedBox(width: ScreenUtil().setWidth(15.0)),
                    Container(
                      width: ScreenUtil().setWidth(400.0),
                      child: Text(
                        '${dataInfo["dest_area"]}',
                        maxLines: 1,
                        overflow: TextOverflow.ellipsis,
                        style: TextStyle(
                            fontSize: ScreenUtil().setSp(28.0),
                            color: Colors.black),
                      ),
                    ),
                  ],
                ),
              ],
            ),
          ),
          Container(
            width: ScreenUtil().setWidth(200.0),
            height: ScreenUtil().setHeight(60.0),
            child: RichText(
              text: TextSpan(
                  text: '¥',
                  style: TextStyle(
                    fontSize: ScreenUtil().setSp(36.0),
                    color: Colors.black,
                  ),
                  children: <TextSpan>[
                    TextSpan(
                      text: '${dataInfo["start_cost"]}',
                      style: TextStyle(
                          fontSize: ScreenUtil().setSp(55.0),
                          color: Colors.black,
                          fontWeight: FontWeight.w700),
                    )
                  ]),
            ),
          ),
        ],
      ),
    );
  }

  // 订单处理
  Widget _orderProcessing(dataInfo) {
    // IndexOrderManagementProvider provider = Provider.of<IndexOrderManagementProvider>(context);
    return Row(
      mainAxisAlignment: MainAxisAlignment.spaceAround,
      children: <Widget>[
        // InkWell(
        //   child: _iconWidget('assets/icon/travelCancel.png', '取消订单'),
        //   onTap: () => _passengerCancelOrder(context),
        // ),
        // InkWell(
        //   child: _iconWidget('assets/icon/travelSharing.png', '行程分享'),
        //   onTap: () {},
        // ),
        // InkWell(
        //   child: _iconWidget('assets/icon/sendNews.png', '发消息'),
        //   onTap: () => NavigatorUtil.jump(context,
        //       '/detailsMessage?orderId=${orderData.driverId}&userName=${Uri.encodeComponent(orderData.driverName)}'),
        // ),
        // InkWell(
        //   child: _iconWidget('assets/icon/CallPoliceIcon.png', '一键报警'),
        //   onTap: () => NavigatorUtil.jump(context, '/oneTouchAlarm'),
        // ),
        InkWell(
          child: Container(
            width: ScreenUtil().setWidth(142.0),
            child: Column(
              children: <Widget>[
                Icon(Icons.near_me,
                    color: Colors.black54, size: ScreenUtil().setSp(40.0)),
                SizedBox(
                  height: ScreenUtil().setWidth(10.0),
                ),
                Text(
                  '导航',
                  style: TextStyle(
                    fontSize: ScreenUtil().setSp(25.0),
                    color: Colors.black54,
                  ),
                ),
              ],
            ),
          ),
          onTap: () {
            if (widget.type == '1') {
              Utils.openGaode(
                  lat: dataInfo["dep_latitude"],
                  lng: dataInfo["dep_longitude"],
                  name: dataInfo["dep_are"]);
            } else {
              Utils.openGaode(
                  lat: dataInfo["dest_latitude"],
                  lng: dataInfo["dest_longitude"],
                  name: dataInfo["dest_are"]);
            }
          },
        ),
        InkWell(
          child: _iconWidget('assets/icon/qrcodeIcon.png', '扫码收款'),
          onTap: () async {
            String cameraScanResult = await scanner.scan();
            print("扫码结果");
            print(cameraScanResult);
            Request.payAllin(
                orderId: dataInfo['order_id'],
                businessCode: 'A0880',
                payType: 'allinscan',
                authcode: cameraScanResult,
                allinPaytype: '');
          },
          // onTap: () => NavigatorUtil.jump(context, '/oneTouchAlarm'),
        ),
        InkWell(
          child: _iconWidget('assets/icon/callIcon.png', '打电话'),
          onTap: () => _makePhoneCall(dataInfo['mobile'].toString()),
        ),
      ],
    );
  }

  /// 拨打电话
  Future<void> _makePhoneCall(String url) async {
    if (await canLaunch('tel:$url')) {
      await launch('tel:$url');
    } else {
      throw 'Could not launch $url';
    }
  }

  /// 取消订单
  void _passengerCancelOrder(context) {
    showDialog(
        context: context,
        builder: (context) => AlertDialog(
              title: Text('确定取消当前订单？'),
              actions: <Widget>[
                FlatButton(
                  child: Text('暂不'),
                  onPressed: () => Navigator.pop(context, false),
                ),
                FlatButton(
                  child: Text('确定'),
                  onPressed: () {
                    NavigatorUtil.goBack(context);
                  },
                ),
              ],
            ));
  }

  //
  Widget _iconWidget(iconAsset, String titleTxt) {
    return Container(
      width: ScreenUtil().setWidth(142.0),
      child: Column(
        children: <Widget>[
          Image.asset(
            iconAsset,
            width: ScreenUtil().setWidth(40.0),
            height: ScreenUtil().setWidth(40.0),
          ),
          SizedBox(
            height: ScreenUtil().setWidth(10.0),
          ),
          Text(
            titleTxt,
            style: TextStyle(
              fontSize: ScreenUtil().setSp(25.0),
              color: Colors.black54,
            ),
          ),
        ],
      ),
    );
  }

  // 监听进行中点击返回按钮
  void showAlertDialog(BuildContext context) {
    NavigatorState navigator =
        context.rootAncestorStateOfType(const TypeMatcher<NavigatorState>());
    debugPrint("navigator is null?" + (navigator == null).toString());

    showDialog(
        context: context,
        builder: (_) => new AlertDialog(
                title: new Text("订单进行中"),
                content: new Text("确定要返回吗"),
                actions: <Widget>[
                  new FlatButton(
                    child: new Text("确定退出"),
                    onPressed: () {
                      Navigator.of(context).pop();
                      eventBus.fire(new SetDispatchOrderList());
                      Navigator.of(context)
                          .popUntil(ModalRoute.withName("/indexPage"));
                    },
                  ),
                  new FlatButton(
                    child: new Text("取消"),
                    onPressed: () {
                      Navigator.of(context).pop();
                    },
                  ),
                ]));
  }

  /// 地图
  Widget _waitingForRideAmap(dataInfo) {
    var markerList = [];
    return Column(
      children: <Widget>[
        Flexible(
          child: AmapView(
            mapType: MapType.Bus,
            showZoomControl: false,
            showCompass: true,
            // 中心点坐标
            centerCoordinate: LatLng(double.parse(dataInfo['dep_latitude']),
                double.parse(dataInfo['dep_longitude'])),
            // 缩放级别
            onMapCreated: (controller) async {
              _amapController = controller;
              if (await PermissionHandlerX.position(context)) {
                var localtionInfo = await LocateInfo.getLocation(context);
                if (localtionInfo == null) return;

                markerList = [
                  {
                    'iconImage': 'assets/icon/startingPointIcon.png',
                    'laction': LatLng(localtionInfo.latLng.latitude,
                        localtionInfo.latLng.longitude),
                  },
                  {
                    'iconImage': 'assets/icon/endIcon.png',
                    'laction': LatLng(num.parse(dataInfo['dep_latitude']),
                        num.parse(dataInfo['dep_longitude'])),
                  },
                ];

                /// 两点直线距离
                await _amapController?.addPolyline(PolylineOption(
                  latLngList: [
                    LatLng(localtionInfo.latLng.latitude,
                        localtionInfo.latLng.longitude),
                    LatLng(num.parse(dataInfo['dep_latitude']),
                        num.parse(dataInfo['dep_longitude'])),
                  ],
                  width: 10,
                  strokeColor: Colors.green,
                ));

                /// 设置两点图片
                final markers = await _amapController?.addMarkers(
                  [
                    for (int i = 0; i < 2; i++)
                      MarkerOption(
                        latLng: markerList[i]['laction'],
                        widget: Container(
                          width: ScreenUtil().setWidth(100.0),
                          height: ScreenUtil().setWidth(100.0),
                          alignment: Alignment.topCenter,
                          child: Image.asset(
                            markerList[i]['iconImage'],
                            width: ScreenUtil().setWidth(50.0),
                            height: ScreenUtil().setWidth(50.0),
                            fit: BoxFit.contain,
                          ),
                        ),
                        anchorV: 0.5,
                        anchorU: 0.5,
                        draggable: true,
                      ),
                  ],
                );
                _markers.addAll(markers);

                /// 将指定的经纬度列表(包括但不限于marker, polyline, polygon等)调整至同一屏幕中显示
                List<LatLng> arr = [
                  LatLng(localtionInfo.latLng.latitude,
                      localtionInfo.latLng.longitude),
                  LatLng(num.parse(dataInfo['dep_latitude']),
                      num.parse(dataInfo['dep_longitude']))
                ];
                _amapController?.zoomToSpan(arr,
                    padding: EdgeInsets.all(ScreenUtil().setWidth(200.0)));
              }
            },
            onMapClicked: (latLng) {
              return;
            },
          ),
        ),
      ],
    );
  }

  @override
  void dispose() {
    _amapController.dispose();
    // _amapController = null;
    _themeModelscription.cancel();
    super.dispose();
  }
}
